package com.ruoyi.system.im;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.system.im.TencentCloudImUtil;
import com.ruoyi.system.domain.ImUser;
import com.ruoyi.system.domain.ImUserMessage;
import com.ruoyi.system.mapper.ImUserMapper;
import com.ruoyi.system.mapper.ImUserMessageMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Component
public class IMUserMessageTask {

    @Autowired
    private ImUserMapper imUserMapper;

    @Autowired
    private ImUserMessageMapper imUserMessageMapper;

    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;

    @Value("${ruoyi.profile}")
    private String profile;

    @Scheduled(cron = "0 0 0 * * ?")
    public void userMessage() throws IOException {
        long nowTime = new Date().getTime() /1000;
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,-1);
        long yesterdayTime=calendar.getTime().getTime() / 1000;
        List<ImUser> imUsers = imUserMapper.selectList(null);
        for (ImUser imUser : imUsers) {
            List<String> userFriendList = tencentCloudImUtil.getUserFriendList(imUser.getUserId());
            for (String toUserId : userFriendList) {
                String s = tencentCloudImUtil.adminGetRoamMsg(imUser.getUserId(), toUserId, 500, yesterdayTime, nowTime, "");
                Map map = JSON.parseObject(s, Map.class);
                if ((Integer)map.get("ErrorCode")==0){
                    //读取成功
                    List<Map> msgList = (List<Map>) map.get("MsgList");
                    for (Map msg : msgList) {
                        boolean b = msgStatus((String) msg.get("MsgKey"));
                        if (!b){
                            //新增一条消息 先判断消息类型
                            List<Map> msgBody = (List<Map>) msg.get("MsgBody");
                            for (Map body : msgBody) {
                                addMsg(body,msg);
                            }
                        }
                    }
                }
            }
        }
    }

    public boolean msgStatus(String msgKey){
        LambdaQueryWrapper<ImUserMessage> userMessageLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userMessageLambdaQueryWrapper.eq(ImUserMessage::getMsgKey,msgKey);
        ImUserMessage imUserMessage = imUserMessageMapper.selectOne(userMessageLambdaQueryWrapper);
        if (ObjectUtils.isEmpty(imUserMessage)){
            return false;
        }else {
            return true;
        }
    }

    public void addMsg(Map body,Map msg) throws IOException {
        String msgType = (String) body.get("MsgType");
        if (msgType.equals("TIMTextElem")||msgType.equals("TIMImageElem")||msgType.equals("TIMVideoFileElem")){
            //仅保存 文本 视频 图片
            Map msgContent = (Map) body.get("MsgContent");
            ImUserMessage userMessage=new ImUserMessage();
            userMessage.setFromUserId((String) msg.get("From_Account"));
            userMessage.setToUserId((String) msg.get("To_Account"));
            userMessage.setMessageType(msgType);
            userMessage.setMessageTime((Integer) msg.get("MsgTimeStamp"));
            userMessage.setMsgKey((String) msg.get("MsgKey"));
            userMessage.setMessage((String) msgContent.get("Text"));
            if (msgType.equals("TIMImageElem")){
                //将图片或者视频保存到服务器本地
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String savePath=profile+"/"+uuid+".jpg";
                List<Map> imageInfoArray = (List<Map>) msgContent.get("ImageInfoArray");
                Map map = imageInfoArray.get(2);
                saveUrlToFile((String)map.get("URL") ,savePath);
                String url = "http://43.128.77.223:8086";
                String fileUrl=url+"/profile/"+uuid+".jpg";
                userMessage.setMessage(fileUrl);
            }else if (msgType.equals("TIMVideoFileElem")){
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String savePath=profile+"/"+uuid+".MP4";
                saveUrlToFile((String) msgContent.get("VideoUrl"),savePath);
                String url = "http://43.128.77.223:8086";
                String fileUrl=url+"/profile/"+uuid+".MP4";
                userMessage.setMessage(fileUrl);
            }
            userMessage.setCreateTime(new Date());
            imUserMessageMapper.insert(userMessage);
        }

    }


    public static void saveUrlToFile(String fileUrl, String savePath) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 获取输入流
            try (InputStream inputStream = connection.getInputStream()) {
                // 创建输出流
                try (OutputStream outputStream = new FileOutputStream(savePath)) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
            }
            System.out.println("文件保存成功：" + savePath);
        } else {
            System.out.println("HTTP 请求失败：" + responseCode);
        }
    }

//    public static String getUrl(){
//        HttpServletRequest request = ServletUtils.getRequest();
//        StringBuffer url = request.getRequestURL();
//        String contextPath = request.getServletContext().getContextPath();
//        String s = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
//        return s;
//    }
}
